package controller;

import com.alibaba.fastjson.JSON;
import entity.Students;
import entity.User_Management;
import service.StudentsService;
import service.User_ManagementService;
import service.impl.StudentsServiceimpl;
import service.impl.User_ManagementServiceimpl;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/User_MangementController")
public class User_MangementController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String op = req.getParameter("op");
        HttpSession session = req.getSession(true);
        PrintWriter out = resp.getWriter();
        User_ManagementService dao = new User_ManagementServiceimpl();
        if ("search".equals(op)) {
            List<User_Management> list = null;
            String username = req.getParameter("username");
            int pageSize = Integer.parseInt(req.getParameter("pageSize"));
            int pageNum  = Integer.parseInt(req.getParameter("page"));
            try {
                // 获取分页数据，添加角色参数
                list = dao.management(username, pageSize, pageNum);
                // 获取总记录数，添加角色参数
                int totalCount = dao.getTotalCount(username);
                // 计算总页数
                int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            
                // 构造返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("data", list);
                result.put("currentPage", pageNum);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);
            
                out.write(JSON.toJSONString(result));
            } catch (SQLException | NamingException | ClassNotFoundException e) {
                e.printStackTrace();
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "查询失败：" + e.getMessage());
                out.print(JSON.toJSONString(error));
            }
        }
        if ("insert".equals(op)) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String role = req.getParameter("role");
            String phone = req.getParameter("phone");
            String sex = req.getParameter("sex");

            try {
                int affectedRows = dao.INSERT(username, password, role, phone, sex);
                // ���� JSON ���
                Map<String, Object> result = new HashMap<>();
                result.put("success", affectedRows > 0);
                result.put("message", affectedRows > 0 ? "成功" : "失败");
                out.print(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message","�û����ظ�");
                out.print(JSON.toJSONString(error));
            }
        }
        if ("update".equals(op)) {
            String userIdStr = req.getParameter("user_id");
            if (userIdStr == null || userIdStr.isEmpty()) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                out.print(JSON.toJSONString(error));
                return;
            }
            int user_id = Integer.parseInt(userIdStr);
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String role = req.getParameter("role");
            String phone = req.getParameter("phone");
            String created_at = req.getParameter("created_at");
            String sex = req.getParameter("sex");
            try {
                int affectedRows = dao.UPDATE(user_id, username, password, role, phone, created_at, sex);
                Map<String, Object> result = new HashMap<>();
                result.put("success", affectedRows > 0);
                result.put("message", affectedRows > 0?"修改成功" : "修改失败");
                out.print(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "ID格式不正确" + e.getMessage());
                out.print(JSON.toJSONString(error));
            }
        }
        if ("delete".equals(op)){
            String user_id = req.getParameter("user_id");
            Map<String, Object> response = new HashMap<>();
            List<User_Management> list=null;
            try {
                int shangchu = dao.delete(Integer.parseInt(user_id));
                out.print(JSON.toJSONString(shangchu));
                response.put("success", shangchu > 0);
                response.put("message", shangchu > 0 ? "删除成功" : "删除失败");
                out.print(JSON.toJSONString(response));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } catch (NamingException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
